package reflection.dynamic_proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ChangLiang
 * @date 2020/3/18
 */
public class BookDaoProxy implements InvocationHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private Object target;

    public Object bind(Object target) {
        this.target = target;

        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object result = null;

        if ("addBook".equals(method.getName())) {
            logger.info("transaction begin");
            result = method.invoke(target, args);
            logger.info("transaction end");
        }

        return result;
    }
}
